package com.wh.wisdomsite.xbox.server.controller.du;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.du.entity.DustProCheckPoint;
import com.wh.wisdomsite.xbox.du.service.IDustProCheckPointService;
import com.wh.wisdomsite.xbox.pojo.du.DustProCheckPointIn;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.us.service.ICompanyService;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 扬尘设备项目检测点配置controller
 *
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.du
 * @date 2018年08月06日 22:45
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/dustProCheckPoint")
public class DustProCheckPointController {
    private static final Log logger = LogFactory.getLog(DustProCheckPointController.class);

       @Autowired
    private IDustProCheckPointService iDustProCheckPointService;

    @Autowired
    private IProjectService iProjectService;

    @Autowired
    private ICompanyService iCompanyService;


    /**
     * 跳转到扬尘设备项目检测点配置
     *
     * @return
     */
    @RequiresPermissions("rules:du_dustProCheckPoint_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index() {
        return "du/dustProCheckPoint/dustProCheckPointList";
    }

    /**
     * 获取扬尘设备项目检测点配置列表
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:du_dustProCheckPoint_find")
    @RequestMapping(value = "/dustProCheckPointList.do")
    public void dustProCheckPointList(HttpServletResponse response, DustProCheckPointIn in) {
        try {
            logger.info("加载扬尘设备项目检测点配置列表-->>开始");
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<DustProCheckPoint> page = new Page<DustProCheckPoint>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<DustProCheckPoint> ewDustProCheckPoint = new EntityWrapper<DustProCheckPoint>();
            ewDustProCheckPoint.setEntity(new DustProCheckPoint());
            if (StringUtils.isNotEmpty(in.getPrId())) {
                ewDustProCheckPoint.eq("d.prId", in.getPrId());
            }
            if (StringUtils.isNotEmpty(in.getDpcpName())) {
                ewDustProCheckPoint.like("d.dpcpName", in.getDpcpName());
            }
            if (StringUtils.isNotEmpty(in.getDeviceId())) {
                ewDustProCheckPoint.eq("d.deviceId", in.getDeviceId());
            }
            if (null != in.getOnLineStatus()) {
                ewDustProCheckPoint.eq("d.onLineStatus", in.getOnLineStatus());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewDustProCheckPoint = UserUtils.setEntityWrapper(ewDustProCheckPoint, "co", "off", "pr");
            }
            ewDustProCheckPoint.orderBy("d.createDate", false);
            Page<Map<String, Object>> checkPointPage = iDustProCheckPointService.getMapsPage(page, ewDustProCheckPoint);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (checkPointPage.getRecords().size() > 0) {
                for (Map<String, Object> dustProCheckPoint : checkPointPage.getRecords()) {
                    JSONObject object = new JSONObject(dustProCheckPoint);
                    Date createDate = (Date) dustProCheckPoint.get("createDate");

                    object.put("createDate", DateTool.format(createDate, "yyyy-MM-dd HH:mm:ss"));
                    if (dustProCheckPoint.get("project") != null) {
                        object.put("project", new JSONObject(dustProCheckPoint.get("project")));
                    }
                    array.put(object);
                }
            }
            json.put("total", checkPointPage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载扬尘设备项目检测点配置列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 扬尘设备项目检测点配置详情
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("dustProCheckPointDesc.do")
    public String dustProCheckPointDesc(String id, String source, HttpServletRequest request) {
        logger.info("扬尘设备项目检测点配置详情-->>开始");
        Map<String, Object> dustProCheckPoint = iDustProCheckPointService.getMapById(id);
        if (dustProCheckPoint.get("createBy") != null) {
            dustProCheckPoint.put("createBy", UserMapManager.getUserLoginNameInMap(dustProCheckPoint.get("createBy").toString()));
        }
        if (dustProCheckPoint.get("updateBy") != null) {
            dustProCheckPoint.put("updateBy", UserMapManager.getUserLoginNameInMap(dustProCheckPoint.get("updateBy").toString()));
        }
        request.setAttribute("dustProCheckPoint", dustProCheckPoint);
        request.setAttribute("source", source);
        logger.info("扬尘设备项目检测点配置详情-->>结束");
        return "du/dustProCheckPoint/dustProCheckPointDesc";
    }

    /**
     * 删除扬尘设备项目检测点配置
     *
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:du_dustProCheckPoint_del")
    @RequestMapping(value = "delDustProCheckPoint.do", method = RequestMethod.GET)
    public void delDustProCheckPoint(String id, HttpServletResponse response) {
        try {
            logger.info("删除扬尘设备项目检测点配置-->>开始");
            iDustProCheckPointService.deleteById(id);
            logger.info("删除扬尘设备项目检测点配置-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除扬尘设备项目检测点配置-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转至添加页面
     *
     * @return
     */
    @RequestMapping("/toDustProCheckPoint.do")
    public ModelAndView toDustProCheckPoint(String id, String source, HttpServletRequest request) {
        logger.info("添加扬尘设备项目检测点配置跳转-->>开始");
        DustProCheckPoint dustProCheckPoint = new DustProCheckPoint();
        if (StringUtils.isNotEmpty(id)) {
            dustProCheckPoint = iDustProCheckPointService.selectById(id);
        }
        request.setAttribute("dustProCheckPoint", dustProCheckPoint);
        request.setAttribute("source", source);
        logger.info("添加修改改扬尘设备项目检测点配置跳转-->>结束");
        return new ModelAndView("du/dustProCheckPoint/dustProCheckPointOption");
    }

    /**
     * 更新或修改扬尘设备项目检测点配置
     *
     * @param dustProCheckPoint
     * @param response
     */
    @RequiresPermissions("rules:du_dustProCheckPoint_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(DustProCheckPoint dustProCheckPoint, HttpServletResponse response) {
        try {
            if (StringUtils.isNotEmpty(dustProCheckPoint.getDpcpId())) {
                logger.info("修改扬尘设备项目检测点配置-->>开始");
                //设置更新者
                dustProCheckPoint.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                dustProCheckPoint.setUpdateDate(new Date());
                iDustProCheckPointService.updateById(dustProCheckPoint);
                logger.info("修改扬尘设备项目检测点配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("更新扬尘设备项目检测点配置成功"));

            } else {
                logger.info("添加扬尘设备项目检测点配置-->>开始");
                //设置创建者
                dustProCheckPoint.setCreateBy(UserUtils.getCurrentUser().getUsId());

                dustProCheckPoint.setCreateDate(new Date());
                iDustProCheckPointService.insert(dustProCheckPoint);
                logger.info("添加扬尘设备项目检测点配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("添加扬尘设备项目检测点配置成功"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加扬尘设备项目检测点配置-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取设备编号
     *
     * @param response
     */
    @RequestMapping(value = "/getDeviceIdList.do")
    public void getDeviceIdList(HttpServletResponse response, String prId) {
        List<DustProCheckPoint> dustProCheckPointList = new ArrayList<DustProCheckPoint>();
        try {
            logger.info("获取设备编号-->>开始");
            EntityWrapper<DustProCheckPoint> ewDustProCheckPoint = new EntityWrapper<DustProCheckPoint>();
            ewDustProCheckPoint.setEntity(new DustProCheckPoint());
            if (StringUtils.isNotEmpty(prId)) {
                ewDustProCheckPoint.eq("prId", prId);
            }
            ewDustProCheckPoint.groupBy("deviceId");
            dustProCheckPointList = iDustProCheckPointService.selectList(ewDustProCheckPoint);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取设备编号-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(dustProCheckPointList));
        logger.info("获取设备编号-->>结束");
    }

    /**
     * 获取各设备总数
     */
    @RequestMapping("/getDeviceTotal.do")
    public void getDeviceTotal(HttpServletResponse response) {
        JSONObject json = new JSONObject();
        //扬尘设备数量
        Integer dustTotal = 0;
        //起重机械设备数量
        Integer craneTotal = 0;
        //视频设备数量
        Integer videoTotal = 0;
        try {
            logger.info("获取各设备总数->>开始");
            //设置条件
            EntityWrapper<DustProCheckPoint> ewDustProCheckPoint = new EntityWrapper<>();
            ewDustProCheckPoint.setEntity(new DustProCheckPoint());
            //若不是管理员设置查询条件
            if (!UserUtils.isSysAdmin()) {
                ewDustProCheckPoint = UserUtils.setEntityWrapper(ewDustProCheckPoint, "co", "off", "pr");
            }
            Map<String, Object> deviceTotal = iDustProCheckPointService.getTotal(ewDustProCheckPoint);
            if(deviceTotal.size() > 0){
                dustTotal = Integer.valueOf(deviceTotal.get("dustTotal").toString());
                craneTotal = Integer.valueOf(deviceTotal.get("craneTotal").toString());
                videoTotal = Integer.valueOf(deviceTotal.get("videoTotal").toString());
            }
            json.put("dustTotal",dustTotal);
            json.put("craneTotal",craneTotal);
            json.put("videoTotal",videoTotal);
            ResManager.getTextOut(response).print(json);
            logger.info("获取各设备总数->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取各设备总数-->>异常Exception " + e.getMessage());
        }
    }

}
